package com.yc.vote.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yc.vote.entity.User;
import com.yc.vote.entity.Vote;
import com.yc.vote.mapper.VoteMapper;
import com.yc.vote.service.BizException;
import com.yc.vote.service.IVoteService;
import com.yc.vote.vo.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 投票系统-题目表-2 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2024-04-14
 */
@RestController
@RequestMapping("/vote/vote")
public class VoteController {

    @Resource
    VoteMapper voteMapper;

    @RequestMapping("query")
    public Map<String, Object> query(String vname,
                                     @RequestParam(defaultValue = "1") int page,
                                     @RequestParam(defaultValue = "5") int size,Integer usid){


        //PageHelper 必须在查询方法前一行执行分页的设置
        //通过插件在后台直接获取数据，设置到p中
        Page<Object> p= PageHelper.startPage(page, size);

        List<Vote> votes = voteMapper.selectLikeVname(vname,usid);

        Map<String,Object> res = new HashMap<>();
        res.put("total",p.getTotal());
        res.put("rows",p);

        return res;
    }

    @Resource
    IVoteService voteServiceImpl;

    //BizException在哪里捕获  异常处理

    @RequestMapping("create")
    public Result create(@RequestBody Vote vote, @SessionAttribute User loginedUser) throws BizException {
        //设置用户id
        vote.setUsid(loginedUser.getId());
//        System.out.println("vote = " + vote);
        voteServiceImpl.create(vote);
        return new Result(1,"添加投票成功",vote);
    }


    @RequestMapping("find")
    public Vote find(Integer id){
        return voteMapper.selectById(id);
    }


    @RequestMapping("del")
    public Result delById(int id,int usid,@SessionAttribute User loginedUser) throws BizException {
        if (loginedUser.getId() != usid){
            return new Result(0,"仅只能删除你自己发布的投票",null);
        }


        voteServiceImpl.dlById(id);
        return new Result(1,"删除投票成功",null);
    }
}
